from rest_framework import serializers
from .models import Order, OrderStatusLog, OrderDocument
from user_app.serializers import UserSerializer
from vehicle_app.serializers import VehicleSerializer
from vehicle_app.models import Vehicle


class OrderVehicleSerializer(serializers.ModelSerializer):
    """订单详情中使用的车辆序列化器，包含经纬度信息"""
    
    driver_name = serializers.CharField(source='user.get_full_name_or_phone', read_only=True)
    driver_phone = serializers.CharField(source='user.phone', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    vehicle_type_display = serializers.CharField(source='get_vehicle_type_display', read_only=True)
    
    class Meta:
        model = Vehicle
        fields = [
            'id', 'license_plate', 'vehicle_type', 'vehicle_type_display',
            'capacity', 'status', 'status_display',
            'driver_name', 'driver_phone',
            'current_location', 'longitude', 'latitude',
            'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'status_display', 'vehicle_type_display',
            'driver_name', 'driver_phone', 'created_at', 'updated_at'
        ]


class OrderDocumentSerializer(serializers.ModelSerializer):
    """订单文档序列化器"""
    
    document_type_display = serializers.CharField(source='get_document_type_display', read_only=True)
    
    class Meta:
        model = OrderDocument
        fields = ['id', 'document_type', 'document_type_display', 'document_url', 'description', 'created_at']
        read_only_fields = ['id', 'document_type_display', 'created_at']


class OrderStatusLogSerializer(serializers.ModelSerializer):
    """订单状态日志序列化器"""
    
    from_status = serializers.ChoiceField(choices=Order.Status.choices, read_only=True)
    to_status = serializers.ChoiceField(choices=Order.Status.choices, read_only=True)
    from_status_display = serializers.CharField(source='get_from_status_display', read_only=True)
    to_status_display = serializers.CharField(source='get_to_status_display', read_only=True)
    operator_name = serializers.CharField(source='operator.phone', read_only=True)
    
    class Meta:
        model = OrderStatusLog
        fields = ['id', 'from_status', 'from_status_display', 'to_status', 'to_status_display', 
                  'operator', 'operator_name', 'created_at']
        read_only_fields = ['id', 'from_status_display', 'to_status_display', 'operator_name', 'created_at']


class OrderSerializer(serializers.ModelSerializer):
    """订单序列化器"""
    
    status = serializers.ChoiceField(choices=Order.Status.choices, read_only=True)
    documents = OrderDocumentSerializer(many=True, read_only=True)
    status_logs = OrderStatusLogSerializer(many=True, read_only=True)
    
    shipper = UserSerializer(read_only=True)
    driver = UserSerializer(read_only=True)
    vehicle = OrderVehicleSerializer(read_only=True)
    
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    payment_status_display = serializers.CharField(source='get_payment_status_display', read_only=True)
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_number', 'vehicle', 'shipper', 'driver',
            'weight', 'goods_type', 'from_location', 'to_location',
            'goods_loading_time', 'goods_expected_arrival_time',
            'freight_fee', 'deposit', 'other_fees', 'total_amount',
            'status', 'status_display', 'payment_status', 'payment_status_display',
            'expected_loading_time', 'actual_loading_time',
            'expected_delivery_time', 'actual_delivery_time',
            'shipper_notes', 'driver_notes', 'confirm_finish',
            'documents', 'status_logs',
            'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'order_number', 'status_display', 'payment_status_display',
            'created_at', 'updated_at', 'confirm_finish'
        ]


class OrderCreateSerializer(serializers.ModelSerializer):
    """订单创建序列化器"""
    
    # 新的参数字段
    total_price = serializers.DecimalField(max_digits=10, decimal_places=2, required=True, help_text='订单总价')
    deadline = serializers.DateTimeField(required=True, help_text='订单截止时间')
    description = serializers.CharField(required=False, allow_blank=True, help_text='订单备注')
    weight = serializers.CharField(required=False, help_text='货物重量，例如："100.00单位吨"')
    type = serializers.CharField(required=False, help_text='货物类型，例如："沥青"')
    from_location = serializers.CharField(required=False, help_text='装货地点')
    to_location = serializers.CharField(required=False, help_text='卸货地点')
    goods_loading_time = serializers.DateTimeField(required=False, help_text='货物装货时间')
    goods_expected_arrival_time = serializers.DateTimeField(required=False, help_text='货物期望到达时间')
    
    class Meta:
        model = Order
        fields = [
            'total_price',
            'deadline',
            'shipper_notes',
            'description',
            'weight',
            'type',
            'from_location',
            'to_location',
            'goods_loading_time',
            'goods_expected_arrival_time',
        ]
    
    def validate(self, data):
        """验证订单创建数据"""
        # 将总价分配给运费，其他费用设为0
        data['freight_fee'] = data.get('total_price', 0)
        data['deposit'] = 0
        data['other_fees'] = 0
        data['total_amount'] = data.get('total_price', 0)
        
        # 设置预计装货和送达时间与截止时间一致
        data['expected_loading_time'] = data.get('deadline')
        data['expected_delivery_time'] = data.get('deadline')
        
        # 处理货主备注，如果提供了description但没有shipper_notes，则使用description
        if not data.get('shipper_notes') and data.get('description'):
            data['shipper_notes'] = data['description']
        elif not data.get('shipper_notes'):
            data['shipper_notes'] = ''
            
        # 映射货物信息字段
        if 'type' in data:
            data['goods_type'] = data.pop('type')
            
        return data


class OrderUpdateSerializer(serializers.ModelSerializer):
    """订单更新序列化器"""
    
    status = serializers.ChoiceField(choices=Order.Status.choices, required=False)
    
    class Meta:
        model = Order
        fields = [
            'freight_fee', 'deposit', 'other_fees',
            'weight', 'goods_type', 'from_location', 'to_location',
            'goods_loading_time', 'goods_expected_arrival_time',
            'expected_loading_time', 'actual_loading_time',
            'expected_delivery_time', 'actual_delivery_time',
            'shipper_notes', 'driver_notes', 'status', 'payment_status'
        ]
    
    def validate(self, data):
        """验证订单更新数据"""
        # 如果更新了金额相关字段，重新计算总金额
        if 'freight_fee' in data or 'other_fees' in data:
            freight_fee = data.get('freight_fee', self.instance.freight_fee)
            other_fees = data.get('other_fees', self.instance.other_fees)
            data['total_amount'] = freight_fee + other_fees
        
        return data


class OrderStatusUpdateSerializer(serializers.Serializer):
    """订单状态更新序列化器"""
    
    # 定义当前有效的订单状态选项
    VALID_ORDER_STATUS_CHOICES = Order.Status.choices
    
    status = serializers.ChoiceField(choices=VALID_ORDER_STATUS_CHOICES, required=True)
    class Meta:
        fields = ['status']


class OrderDocumentCreateSerializer(serializers.ModelSerializer):
    """订单文档创建序列化器"""
    
    class Meta:
        model = OrderDocument
        fields = ['document_type', 'document_url', 'description']


class OrderListSerializer(serializers.ModelSerializer):
    """订单列表序列化器"""
    

    
    status = serializers.CharField(read_only=True)
    shipper_name = serializers.CharField(source='shipper.phone', read_only=True)
    driver_name = serializers.CharField(source='driver.phone', read_only=True)
    vehicle_license_plate = serializers.CharField(source='vehicle.license_plate', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    payment_status_display = serializers.CharField(source='get_payment_status_display', read_only=True)
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_number', 'shipper_name', 'driver_name',
            'vehicle_license_plate',
            'weight', 'goods_type', 'from_location', 'to_location',
            'goods_loading_time', 'goods_expected_arrival_time',
            'freight_fee', 'total_amount',
            'status', 'status_display', 'payment_status', 'payment_status_display',
            'expected_loading_time', 'expected_delivery_time',
            'confirm_finish',
            'created_at'
        ]
        read_only_fields = [
            'id', 'order_number', 'shipper_name', 'driver_name',
            'vehicle_license_plate',
            'status_display', 'payment_status_display', 'confirm_finish',
            'created_at'
        ]